package com.sendpo.zjx.sendpo.fragment.privatedingdan;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.activity.GeneicStoreInfoActivity;
import com.sendpo.zjx.sendpo.activity.MerchandiseEvalutatetActivity;
import com.sendpo.zjx.sendpo.domain.PrivateDingdanDomain;
import com.sendpo.zjx.sendpo.domain.ProduceOrderDomain;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONObject;
import org.xutils.common.Callback;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by zjx on 2018
 */

public class DaifahuoFragment extends BaseDingdanFragment {
    public int currentlastitem = 0;
    public boolean lastloading = false;
    private LinearLayoutManager lm;
    private int pagenow = 1;
    @BindView(R.id.pulltofresh)
    public PullToRefreshLayout pulltofresh;
    @BindView(R.id.recyclerview)
    PullableRecyclerView recyclerview;
    View rootView = null;
    private RecylcerMessageAdaper adpter;

    public View initView()
    {
        View localView = View.inflate(this.mActivity, R.layout.fragment_dingdan_all, null);
        ButterKnife.bind(localView, this.mActivity);
        return localView;
    }

    public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
    {
        if (this.rootView == null) {
            this.rootView = super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);
            ButterKnife.bind(this, this.rootView);
            initData();
        }
        return this.rootView;
    }

    private void initData() {
        this.lm=new LinearLayoutManager(mActivity, OrientationHelper.VERTICAL,false);
        this.recyclerview.setLayoutManager(this.lm);
        List<PrivateDingdanDomain.DataBean> dataBeans=new ArrayList<>();
        recyclerview.setAdapter(adpter=new RecylcerMessageAdaper(mActivity,dataBeans));
        pulltofresh.setPullDownEnable(true);
        pulltofresh.setPullUpEnable(true);
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener()
        {
            public void onLoadMore(PullToRefreshLayout paramAnonymousPullToRefreshLayout)
            {
                  pagenow++;
                 append(DaifahuoFragment.this.pagenow,"2");
            }

            public void onRefresh(PullToRefreshLayout paramAnonymousPullToRefreshLayout) {
                    pagenow=1;
                query(DaifahuoFragment.this.pagenow,"2");
            }
        });
        this.pulltofresh.autoRefresh();
    }



    public class RecylcerMessageAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
        public List<PrivateDingdanDomain.DataBean> dataBeen;
        public LayoutInflater inflater;
        public RecylcerMessageAdaper(Context context, List<PrivateDingdanDomain.DataBean> dataBeen){
            this.dataBeen=dataBeen;
            this.inflater=LayoutInflater.from(context);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new IndexHoler(this.inflater.inflate(R.layout.layout_dingdan_listitem, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih= (IndexHoler) holder;
            final PrivateDingdanDomain.DataBean produce=dataBeen.get(position);
            Glide.with(mActivity)
                    .load(produce.getImg())
                    .asBitmap()
                    .centerCrop()
                    .animate(R.anim.fade_in)
                    .placeholder(R.color.default_lightgray)
                    .into(ih.produce);
            ih.num.setText("数量：" + produce.getCount() + "");
            ih.produce_name.setText(produce.getTitle() + "");
            DecimalFormat decimalFormat=new DecimalFormat("");
            ih.currentprice_tv.setText("现价：¥" + decimalFormat.format(Double.parseDouble(produce.getPrice()+"")));
            if(produce.getDeliveryType()==0){
                ih.shouhuotype.setText("收货方式：配送");
                ih.num_tv.setText("共" + produce.getCount() + "件商品");
            }else{
                ih.shouhuotype.setText("收货方式：自取");
                ih.num_tv.setText("共" + produce.getCount() + "件商品");
            }
            ih.redirectstore_bt.setOnClickListener(new View.OnClickListener() {
                public void onClick(View paramAnonymousView)
                {
//                     Map<String,Object> map = new HashMap();
//                     map.put("merchandiseId",produce.getProductId());
//                     Tools.redirectActivity(mActivity, GeneicStoreInfoActivity.class, map);
                }
            });
            ih.price_tv.setText("实付款：¥" +  decimalFormat.format(Double.parseDouble(produce.getPrice()+"")));
            switch (produce.getOrderStatus()){
                case 1:
                    ih.readby_bt.setVisibility(View.GONE);
                    ih.gofukuan_bt.setVisibility(View.VISIBLE);
                    ih.gofukuan_bt.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View paramAnonymousView) {
                            mActivity.showPay(produce.getOrderId()+"");
                        }
                    });
                    ih.close_bt.setVisibility(View.VISIBLE);
                    ih.close_bt.setOnClickListener(new View.OnClickListener()
                    {
                        public void onClick(View paramAnonymousView) {
                            cancel(produce.getOrderId()+"",position);
                        }
                    });
                    ih.tuihuo_bt.setVisibility(View.GONE);
                    ih.info_bt.setVisibility(View.GONE);
                    ih.gopinjia_bt.setVisibility(View.GONE);
                    break;
                case 2:
                    ih.readby_bt.setVisibility(View.GONE);
                    ih.gofukuan_bt.setVisibility(View.GONE);
                    ih.close_bt.setVisibility(View.GONE);
                    ih.info_bt.setVisibility(View.GONE);
                    ih.gopinjia_bt.setVisibility(View.GONE);
                    ih.tuihuo_bt.setVisibility(View.VISIBLE);
                    ih.tuihuo_bt.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            refundMoney(produce.getOrderId()+"",position);
                        }
                    });
                    break;
                case 4:
                    ih.gofukuan_bt.setVisibility(View.GONE);
                    ih.close_bt.setVisibility(View.GONE);
                    ih.tuihuo_bt.setVisibility(View.GONE);
                    ih.gopinjia_bt.setVisibility(View.GONE);
                    ih.info_bt.setVisibility(View.GONE);
                    ih.readby_bt.setVisibility(View.VISIBLE);
                    ih.readby_bt.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            readyoder(produce.getOrderId()+"",position);
                        }
                    });
                    break;
                default:
                    ih.gofukuan_bt.setVisibility(View.GONE);
                    ih.close_bt.setVisibility(View.GONE);
                    ih.tuihuo_bt.setVisibility(View.GONE);
                    ih.gopinjia_bt.setVisibility(View.GONE);
                    ih.info_bt.setVisibility(View.GONE);
                    ih.readby_bt.setVisibility(View.GONE);
                    break;

            }
        }


        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public void delete(int paramInt)
        {
            this.dataBeen.remove(paramInt);
            notifyDataSetChanged();
        }
        public void init()
        {
            this.dataBeen.removeAll(this.dataBeen);
            notifyDataSetChanged();
        }
        public void initAppend(List<PrivateDingdanDomain.DataBean> paramList)
        {
            this.dataBeen.addAll(paramList);
            notifyDataSetChanged();
        }

        public void initRefresh(List<PrivateDingdanDomain.DataBean> paramList)
        {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(paramList);
            notifyDataSetChanged();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public CircleImageView cir_icon;
            public Button close_bt;
            public Button confirmshouhuo_bt;
            public TextView currentprice_tv;
            public Button gofukuan_bt;
            public Button gopinjia_bt;
            public Button info_bt;
            public TextView jifen_money;
            public TextView jifentype;
            public RelativeLayout merchats_head_bt;
            public TextView name;
            public TextView num;
            public TextView num_tv;
            public TextView originprice_tv;
            public TextView price_tv;
            public ImageView produce;
            private TextView produce_name;
            public RelativeLayout redirectstore_bt;
            public View rootView;
            public TextView shouhuotype;
            public Button tuihuo_bt;
            public Button readby_bt;
            public IndexHoler(View rootView) {
                super(rootView);
                readby_bt=rootView.findViewById(R.id.readby_bt);
                tuihuo_bt=rootView.findViewById(R.id.tuihuo_bt);
                this.gopinjia_bt = rootView.findViewById(R.id.gopinjia_bt);
                this.info_bt = rootView.findViewById(R.id.info_bt);
                this.confirmshouhuo_bt =  rootView.findViewById(R.id.confirmshouhuo_bt);
                this.jifen_money =  rootView.findViewById(R.id.jifen_money);
                this.jifentype = rootView.findViewById(R.id.jifentype);
                this.redirectstore_bt =  rootView.findViewById(R.id.redirectstore_bt);
                this.originprice_tv =  rootView.findViewById(R.id.originprice_tv);
                this.originprice_tv.getPaint().setFlags(8);
                this.originprice_tv.getPaint().setFlags(16);
                this.originprice_tv.getPaint().setAntiAlias(true);
                this.originprice_tv.getPaint().setFlags(17);
                this.name = rootView.findViewById(R.id.name);
                this.cir_icon =  rootView.findViewById(R.id.cir_icon);
                this.merchats_head_bt = rootView.findViewById(R.id.merchats_head_bt);
                this.rootView = rootView;
                this.produce = rootView.findViewById(R.id.produce);
                this.produce_name =  rootView.findViewById(R.id.produce_name);
                this.num =  rootView.findViewById(R.id.num);
                this.currentprice_tv =  rootView.findViewById(R.id.currentprice_tv);
                this.shouhuotype =rootView.findViewById(R.id.shouhuotype);
                this.num_tv = rootView.findViewById(R.id.num_tv);
                this.price_tv =  rootView.findViewById(R.id.price_tv);
                this.gofukuan_bt = rootView.findViewById(R.id.gofukuan_bt);
                this.close_bt =rootView.findViewById(R.id.close_bt);
                originprice_tv.setVisibility(View.GONE);
            }
        }
        public void cancel(String orderId, final int position){
            Map<String,String> map=new HashMap<>();
            map.put("id",""+orderId);
            Xutils.GET(HttpUrl.customizecancelOrder, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    System.out.println("********************************result"+result);
                    try {
                        JSONObject jsonObject=new JSONObject(result);
                        if(jsonObject.getBoolean("flag")){
                            delete(position);
                            Toast.makeText(getActivity().getApplicationContext(),"取消订单成功",Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(getActivity().getApplicationContext(),"取消订单失败",Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Toast.makeText(getActivity(),"请稍后再试",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
        public void refundMoney(String orderId, final int position){
            List<User> userList=Xutils.queryAll(mActivity.getApplication(),User.class);
            Map<String,String> map=new HashMap<>();
            map.put("id",""+orderId);
            map.put("userId",""+userList.get(0).getUserId());
            Xutils.GET(HttpUrl.customizerefundMoney, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    System.out.println("********************************result"+result);
                    try {
                        JSONObject jsonObject=new JSONObject(result);

                        if(jsonObject.getBoolean("flag")){
                            delete(position);
                            Toast.makeText(getActivity().getApplicationContext(),"退款申请成功",Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(getActivity().getApplicationContext(),"退款申请失败",Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Toast.makeText(getActivity(),"请稍后再试",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
        public void readyoder(String orderId,final int position){
            Map<String,String> map=new HashMap<>();
            map.put("id",""+orderId);
            Xutils.GET(HttpUrl.customizeconfirmReceipt, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    System.out.println("********************************result"+result);
                    try {
                        JSONObject jsonObject=new JSONObject(result);

                        if(jsonObject.getBoolean("flag")){
                            delete(position);
                            Toast.makeText(getActivity().getApplicationContext(),"确认收货成功",Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(getActivity().getApplicationContext(),"确认收货失败",Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Toast.makeText(getActivity(),"请稍后再试",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
    }


    public void query(int pagenow,String orderState) {
        List<User> userList= Xutils.queryAll(getActivity().getApplication(), User.class);
        Map<String,String> map=new HashMap<>();
        map.put("page", pagenow + "");
        map.put("pageSize","10");
        map.put("userId", userList.get(0).getUserId() + "");
        if(!TextUtils.isEmpty(orderState)){
            map.put("status", orderState);
        }
        Xutils.GET(HttpUrl.customizegetUserOrderList, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                Gson gson=new Gson();
                PrivateDingdanDomain domain=gson.fromJson(result,PrivateDingdanDomain.class);
                if(domain.isFlag()){
                    if(domain!=null||domain.getData()!=null&&domain.getData().size()!=0){
                        if(domain.getData()!=null&&domain.getData().size()!=0){
                            if(adpter==null){
                                recyclerview.setAdapter(adpter=new RecylcerMessageAdaper(mActivity,domain.getData()));
                            }else{
                                adpter.initRefresh(domain.getData());
                            }
                        }
                    }else{
                        adpter.init();

                    }
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });



    }
    public void append(int pagenow,String orderState) {
        List<User> userList= Xutils.queryAll(getActivity().getApplication(), User.class);
        Map<String,String> map=new HashMap<>();
        map.put("page", pagenow + "");
        map.put("pageSize","10");
        map.put("userId", userList.get(0).getUserId() + "");
        if(!TextUtils.isEmpty(orderState)){
            map.put("status", orderState);
        }
        Xutils.GET(HttpUrl.customizegetUserOrderList, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                Gson gson=new Gson();
                PrivateDingdanDomain domain=gson.fromJson(result,PrivateDingdanDomain.class);
                if(domain.isFlag()){
                    if(domain!=null||domain.getData()!=null&&domain.getData().size()!=0){
                        if(domain.getData()!=null&&domain.getData().size()!=0){
                            if(adpter==null){
                                recyclerview.setAdapter(adpter=new RecylcerMessageAdaper(mActivity,domain.getData()));
                            }else{
                                adpter.initRefresh(domain.getData());
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

}
